package de.gameduell.framework.gui.animation {
	import flash.events.EventDispatcher;

	import de.gameduell.framework.gui.animation.Tweenable;

	import fl.transitions.TweenEvent;	

	/**
	 * @author cbra
	 */
	public class ChainedTween extends EventDispatcher implements Tweenable {

		public var tweenList:Array;
		private var _isPlaying:Boolean;

		public function ChainedTween(aTweenList:Array = null) {
			tweenList = aTweenList == null ? new Array() : aTweenList;
			TweenManager.getInstance().add(this);
		}

		/**
		 * adds a tween to the tween list
		 */
		public function addTween(tween:Tweenable):void {
			tweenList.push(tween);
		}

		/**
		 * starts all tweens in the tween list
		 */
		public function start():void {
			_isPlaying = true;
			if(tweenList.length > 0) {
				tweenList[0].start();
				tweenList[0].addEventListener(TweenEvent.MOTION_FINISH, onMotionFinished);
			}
		}

		/**
		 * stops all tweens in the tween list
		 */
		public function stop():void {
			_isPlaying = false;
			if(tweenList.length > 0) {
				tweenList[0].stop();
			}
		}

		private function onMotionFinished(event:TweenEvent):void {
			tweenList.shift();
			if(tweenList.length > 0) {
				tweenList[0].start();
				tweenList[0].addEventListener(TweenEvent.MOTION_FINISH, onMotionFinished);
			}else {
				_isPlaying = false;
				dispatchEvent(new TweenEvent(TweenEvent.MOTION_FINISH, event.time, event.position, event.bubbles, event.cancelable));				
			}
		}
		
		public function get isPlaying():Boolean {
			return _isPlaying;
		}
	}
}
